import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> list = new ArrayList<>();
        HashMap<String, Integer> hashMap1 = new HashMap<>();
        HashMap<String, Integer> hashMap2 = new HashMap<>();

        for (int i = 0; i < words.length; i++) {
            hashMap1.put(words[i], hashMap1.getOrDefault(words[i], 0) + 1);
        }
        int left = 0, right = 0;
        for (int i = 0; left < words[0].length(); i++) {
            while (right < s.length() && right + words[0].length() <= s.length()) {
                String t = s.substring(right, right + words[0].length());
                hashMap2.put(t, hashMap2.getOrDefault(t, 0) + 1);
                right += words[0].length();

                if ((right - left) / words[0].length() > words.length) {
                    String c = s.substring(left, left + words[0].length());
                    if (hashMap2.get(c) == 1) {
                        hashMap2.remove(c);
                    } else {
                        hashMap2.put(c, hashMap2.get(c) - 1);
                    }
                    left += words[0].length();
                }

                if (hashMap1.equals(hashMap2)) {
                    list.add(left);
                }
            }
            left = i + 1;
            right = i + 1;
            hashMap2 = new HashMap<>();
        }
        return list;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.findSubstring("wordgoodgoodgoodbestword", new String[]{"word", "good", "best", "good"}));
    }
}